<template>
  <!-- components插件 -->
  <el-dialog :visible="settingsVisible" :title="myIndex > -1? '编辑溯源环节' : '新增溯源环节'" width="40%" @close="closeDialog">
    <!-- 商品分类 -->
    <!-- {{ settingForm }} -->
    <el-form ref="addStep" :rules="rule" :model="settingForm">
      <el-form-item :label-width="labeWidth" label="环节名称" prop="linkName" maxlength="10">
        <el-col :span="18" >
          <el-input v-model="settingForm.linkName" maxlength="10" placeholder="请填写环节名称"/>
        </el-col>
      </el-form-item>
      <el-form-item :label-width="labeWidth" label="说明" prop="description">
        <el-col :span="18" >
          <el-input v-model="settingForm.description" type="textarea" maxlength="100"/>
        </el-col>
      </el-form-item>
      <el-form-item :label-width="labeWidth" label="类型" prop="type">
        <el-col :span="18" >
          <el-select v-model="settingForm.type" placeholder="请选择类型" @change="choose">
            <el-option :label="'文字'" :value="0"/>
            <el-option :label="'图片'" :value="1"/>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item
        v-show="settingForm.type === 0"
        :label-width="labeWidth"
        :rules="[
          {required: true, message:'请输入内容', trigger: 'blur'}
        ]"
        prop="content"
        label="文字">
        <el-col :span="18" >
          <el-input
            v-model="settingForm.content"
            placeholder="请输入内容"
            maxlength="200"
            style="margin-top:10px"
            type="textarea"/>
        </el-col>
      </el-form-item>
      <el-form-item
        v-show="settingForm.type === 1"
        :label-width="labeWidth"
        :rules="[
          {required: true, message:'请选择图片', trigger: 'blur'}
        ]"
        prop="content"
        label="图片">
        <el-col :span="18" >
          <!-- <el-input v-model="settingForm.title" type="text" placeholder="请输入标题"/> -->
          <div style="width:302px; margin-top:10px" class="fl">
            <div class="thumbnail">
              <img v-show="settingForm.content" :src="settingForm.content" alt="">
            </div>
            <div class="uploadBox">
              <el-upload
                ref="picUpload"
                :before-remove="beforeRemove"
                :before-upload="beforeAvatarUpload"
                :on-success="(file, filelist) => change('coverImg', file, filelist)"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
                :data="uploadData"
                :action="actionUrl"
                :with-credentials= "false"
                v-model="settingForm.content"
                multiple
                class="upload-demo fl"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif,.Gif">
                <el-button size="small" type="primary" plain>选择图片</el-button>
              </el-upload>
              <el-button class="btn_clear fr" size="small" type="info" plain @click="clearPic()">清除</el-button>
            </div>
          </div>
        </el-col>
      </el-form-item>
      <div class="bottomBtn">
        <el-button type="primary" @click="submitForm('addStep')">确定</el-button>
        <el-button type="info" @click="closeDialog">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import config from '@/utils/config';
import { Message } from 'element-ui'
import { vipInfoAll } from '@/api/product'
// <sendGoods :send-goods-visible.sync="sendGoods" :send-goods-index="sendGoodsIndex" :send-goods-id="sendGoodsId"/>
const checkType = (rule, value, callback) => {
//   if (!checkNum(value)) {
//     callback(new Error())
//   }
  console.log('校验类型：', value)
  callback();
};
export default {
  props: {
    settingsVisible: {
      type: Boolean,
      required: true
    },
    myIndex: {
      type: Number,
      required: true
    },
    dialogData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      labeWidth: '80px',
      goodTypesForm: {},
      settingForm: {
        linkName: '', // 环节名称
        description: '', // 说明
        type: '', // 类型：0 文字，1 图片
        content: '' //  type = 0 录入文字，当 type = 1 录入图片地址
      },
      uploadData: {
        key: '',
        token: ''
      },
      tinymceDis: false,
      actionUrl: config.BaseUrl + '/storage/create',
      fileList: [],

      rule: {
        linkName: [
          { required: true, message: '请填写环节名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写说明', trigger: 'blur' }
          //  { validator: checkType, message: '请输入整数', trigger: 'blur' }
        ],
        usableStatus: [
          { required: true, message: '请选择是否启用', trigger: 'blur' }
        ],
        discount: [
          { required: true, message: '请填写会员折扣', trigger: 'blur' },
          { pattern: /^(\d+)(.\d{0,2})?$/, message: '请输入正确的数字，并且小数点后最多保留两位数字', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    titleName() {
      console.log(this.settingMode)
      const titleMap = {
        'addStepGoods': '商品溯源环节模版',
        'addStep': '环节'
      }
      return titleMap[this.settingMode]
    }
  },
  watch: {
    myIndex(val) {
      if (val > -1) {
        this.settingForm = Object.assign({}, this.dialogData)
      } else {
        this.settingForm = {}
      }
    }
  },
  mounted() {
    // if (this.settingMode === 'discount' || this.settingMode === 'membersRebate') {
    //   // this.getConstantPercent()
    //   this.getMomList()
    // }
  },
  methods: {
    // getMomList() {
    //   vipInfoAll().then(res => {
    //     if (res.code === '200') {
    //       this.momList = res.data
    //     } else {
    //       Message.error(res.message)
    //     }
    //   })
    // },
    choose(val) {
      console.log(val)
      this.settingForm.content = ''
      this.$refs.addStep.clearValidate('type') // 去掉类型校验提示
    },
    submitForm(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          // 向父级插件冒一个‘updataParent’ 的方法, 并且把填好的数据带过去， 到父级去做处理
          this.$emit('updataParent', this.settingForm)
          this.$emit('update:myIndex', -1)
          this.settingForm = {}
          this.closeDialog()
        }
      })
    },
    closeDialog() {
      this.$emit('update:settingsVisible', false)
      this.$emit('update:myIndex', -1)
    },
    beforeRemove(file, fileList) {
      console.log('file:::', file)
      console.log('fileList:::', fileList)
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`).then(() => {
          // let index = fileList
          console.log()
        })
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPEG && !isJPG && !isGIF) {
        this.$message.error('上传头像图片只能是 jpg、png、jpeg、gif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
      console.log('beforeAvatarUpload:', file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    clearPic() {
      this.$confirm('确定删除此图吗？').then(() => {
        this.settingForm.content = ''
        this.$refs.picUpload.clearFiles()
      }).catch(() => {})
    },
    change(type, file, fileList) {
      this.isUpload = true
      this.fileList = [];
      console.log('fileList:::', fileList)
      console.log('config.ImgUrl:::', config.ImgUrl)
      if (Number(fileList.response.code) === 200) {
        let obj;
        if (fileList.response.code === '200') {
          this.settingForm.content = fileList.response.data.url
        }
        Message.success('图片上传成功')

        // this.$store.dispatch('addListenerCoverImg', obj).then(() => {
        //   Message.success('图片上传成功')
        // }).catch((err) => {
        //   Message.error(err.err)
        // })
      }
    }
  }
}
</script>
<style scope>
.bottomBtn{
    height: 80px;
    padding-top: 20px;
    width:100%;
    text-align: center;
    border-top: 1px solid #ddd
}
.bottomBtn button{
    display: inline-block;
}
select{
    width:100%
}
.thumbnail{
        width: 302px;
        height: 200px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
    }

    .thumbnail img{
        width: 100% ;
    }
    .uploadBox{
        width: 100%;
        height: 40px;
        position: relative;
    }
    .btn_clear{
        position: absolute;
        bottom: 0px;
        right: 0;
        /* margin-top: 4px; */
        padding: 10px 30px;
    }
</style>
